package q636_exclusiveTime;

import java.util.List;

public class Solution_2 {
    /*
    用一个二维数组和一个指针即可模拟该栈 原理和solution1是一致的
     */
    public int[] exclusiveTime(int n, List<String> logs) {
        int[] res = new int[n];
        int[][] stack = new int[501][];
        int p = -1;
        for (String log : logs) {
            // 函数
            int idx = Integer.parseInt(log.substring(0, log.indexOf(':')));
            // 时间类型
            String type = log.substring(log.indexOf(':') + 1, log.lastIndexOf(':'));
            // 时间戳
            int timestamp = Integer.parseInt(log.substring(log.lastIndexOf(':') + 1));
            if ("start".equals(type)) {
                if (p >= 0) {
                    res[stack[p][0]] += timestamp - stack[p][1];
                    stack[p][1] = timestamp;
                }
                ++p;
                stack[p] = new int[]{idx, timestamp};
            } else {
                int[] curFunc = stack[p];
                res[stack[p][0]] += timestamp - stack[p][1] + 1;
                --p;
                if (p >= 0) {
                    stack[p][1] = timestamp + 1;
                }
            }
        }
        return res;
    }
}
